# -*- coding: utf-8 -*-
import requests
import re
import xlwt
import xlrd
# python2 和 python3的兼容代码
try:
    import cookielib
    print("user cookielib in python2.")
except:
    import http.cookiejar as cookielib
    print("user cookielib in python3.")

def read_excel():
 ExcelFile=xlrd.open_workbook('test2.xls')
 sheet=ExcelFile.sheet_by_name('test')
 cols=sheet.col_values(2)#第二列内容

 fileList=[]
 tranList=[]
 language=['zh','hk','en','ja','es','pt','br','fr','de','ko']
 languageRow=4
 for lang in language:
  tranList.append(sheet.col_values(languageRow))
  f = open(lang+'.txt','wb')
  f.truncate()
  fileList.append(f)
  languageRow+=1

 row=0
 for name in cols:
   type =sheet.cell_type(row,1)
   if(type==1 and name!=""):
     languageIndex=0
     for lang in language:
      txt =tranList[languageIndex][row]
      value = txt.replace('%@', '%s')
      text = '<' + 'string name=' + '\"' + name.strip() + '\"' + '>' + value.strip() + '</string>' + '\n'
      fileList[languageIndex].write((text.encode("utf-8")))
      languageIndex+=1
   row+=1

 for fileHandle in fileList:
  fileHandle.close()

workbook = xlwt.Workbook()
sheet1=workbook.add_sheet('test',cell_overwrite_ok=True)

# session代表某一次连接
mafengwoSession = requests.session()
# 因为原始的session.cookies 没有save()方法，所以需要用到cookielib中的方法LWPCookieJar，这个类实例化的cookie对象，就可以直接调用save方法。

userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
header = {
    "Referer": "http://wiki.orvibo.com:8190/login.action?os_destination=%2Fpages%2Fviewpage.action%3FpageId%3D43352241&permissionViolation=true",
    'User-Agent': userAgent,
}

def mafengwoLogin(account, password):
    print("开始模拟登陆Confluence")
    postUrl = "http://wiki.orvibo.com:8190/dologin.action"
    postData = {
        "os_username":account,
        "os_password":password,
        "login": "登录",
        "os_destination": "/pages/viewpage.action?pageId=47251585"
    }
    # 使用session直接post请求
    responseRes = mafengwoSession.post(postUrl, data = postData, headers = header)
    resp = mafengwoSession.get("http://wiki.orvibo.com:8190/pages/viewpage.action?pageId=47251585", headers=header, allow_redirects=False)
    title = re.findall('"table-wrap">(.*?)</tbody>', resp.text, re.S)
    print(title)
    colgroup = re.findall('<colgroup>(.*?)</colgroup>', title[0], re.S)
    # colArray = re.findall('<col/>',colgroup[0],re.S)
    colLen =14
    print(colLen)
    content = re.findall('"confluenceTd">(.*?)</td>', title[0], re.S)
    row=1
    col=1
    for line in content:
        if line.__contains__("span")and line.__contains__(');">'):
            start = line.find(');">')
            end = line.find('</span>')
            line = line[start+4:end]
        if line.__contains__('<p>'):
            start = line.find('<p>')
            end = line.find('</p>')
            line = line[start+3:end]
        line = line.strip()
        line = line.replace('％', '%')
        line = line.replace('<span>','')
        line = line.replace('</span>','')
        line = line.replace('<pre>','')
        line = line.replace('</pre>','')
        line = line.replace('\'','\\\'')
        if line != "":
          sheet1.write(row, col, line)
          print(line)
          print("\n")
        col+=1
        if(col>colLen-1):
            col=1
            row+=1
        workbook.save('test2.xls')
if __name__ == "__main__":
    # 从返回结果来看，有登录成功
    mafengwoLogin("wuliquan", "wjwlqyjira")
    read_excel()